import util from "$util"

// 线下配置
const devConfig = {
  name: "dev",
  baseURL: "http://10.28.245.10:8081/",

  // baseURL: "", // must be empty, meaning localhost, which proxys to the real url in build/webpack.dev.js
  // baseURL: "http://192.168.3.229:8099",
}

// 线上配置
const productionConfig = {
  name: "production",
  baseURL: "http://10.28.245.10:8081",
}

// ================================================================================
// 切换线上/线下的配置

// current version in production is 1.0.8
//设置版本号
const APP_VERSION = "1.0.9"
//设置接口ip
// const AppConfig = devConfig
const AppConfig = productionConfig
//自定义数据
let mockMap = null
 //mockMap = require("./mock") // 如果要用模拟的数据，就打开这行的注释

// ================================================================================
import axios from "axios"

const axClient = axios.create({
  baseURL: AppConfig.baseURL,
  timeout: 10000,
  /* headers: {
    "Content-Type": "text/plain",
  }, */
  // withCredentials: true,
})

let loginToken = ""

function setLoginToken(token) {
  loginToken = token
}

// ================================================================================
import { Indicator } from "mint-ui"

function downloadApk(downUrl) {
  Indicator.open({
    text: "下载中...",
  })

  /* if (AppConfig.name !== "production") {
    downUrl = "http://172.16.121.198:9001/app-debug.apk"
  } else {
    downUrl = ""
  } */

  axios.get(downUrl, {
      responseType: "arraybuffer",
    })
    .then((resp) => {
      writeApk(resp.data)
    })
    .catch((err) => {
      console.log(err)
    })
}

function writeApk(data) {
  const apkName = "les.apk"
  window.resolveLocalFileSystemURL(cordova.file.externalCacheDirectory,
    (dir) => {
      dir.getFile(apkName, {
        create: true,
        exclusive: false,
      }, (file) => {
        writeFile(file, data, () => {
          Indicator.close()
          Indicator.open("等待安装中...")
          window.plugins.intentShim.startActivity({
            action: window.plugins.intentShim.ACTION_VIEW,
            url: file.nativeURL,
            type: "application/vnd.android.package-archive",
          }, () => {}, () => {})
        })
      })
    })
}

function writeFile(fileEntry, data, onSuccess, onError) {
  fileEntry.createWriter((fileWriter) => {
    fileWriter.onwriteend = onSuccess
    if (!onError) {
      fileWriter.onerror = (e) => {
        console.log("Failed file write: " + e.toString())
      }
    }
    let newData = new Blob([data], { type: "application/octet-stream" })
    fileWriter.write(newData)
  })
}

function hasNewVersion() {
  // for dev
  /* if (AppConfig.name !== "production") {
    const checkUrl = "http://172.16.121.198:9001/check-version"
    return axios.get(checkUrl).then((resp) => {
      return true
    })
  } */

  // for production
  const checkUrl = AppConfig.baseURL + "/api/UpdateForPDA/GetUpdateForPDA"
  return axios.post(checkUrl, {
    timeout: 10000,
  }).then((resp) => {
    try {
      let data = resp.data.data

      let forceUpdate = (data.Isforceupdate === 1)
      let downUrl = data.Url

      let newList = data.Version.split(".")
      let curList = APP_VERSION.split(".")
      let hasNewVersion = false
      for (let i = 0; i < curList.length; i++) {
        if (curList[i] == undefined) {
          curList[i] = "0"
        }
        if (newList[i] == undefined) {
          newList[i] = "0"
        }
        let curNum = parseInt(curList[i])
        let newNum = parseInt(newList[i])
        if (curNum < newNum) {
          hasNewVersion = true
          break
        } else if (curNum > newNum) {
          break
        }
      }

      return {
        hasNewVersion,
        forceUpdate,
        downUrl,
      }
    } catch (e) {
      console.log("error in check-version: " + e)
    }
  })
}

// ================================================================================
module.exports = {
  setLoginToken,

  APP_VERSION,
  AppConfig,
  hasNewVersion,
  downloadApk,

  ax(path, postData = {}, config) {
    if (mockMap) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          try {
            resolve(mockMap[path](postData))
          } catch (err) {
            reject(err)
          }
        }, 1000)
      })
    }

    if (loginToken) {
      postData.token = loginToken
    } else {
      let user = util.loginInfo.getUser()
      if (user && user.token) {
        setLoginToken(user.token)
        postData.token = loginToken
      }
    }

    /* if (path === "/api/Tran/Processed") {
      console.log(JSON.stringify(postData))
      return
    } */

    return axClient.post(path, postData, config)
      .then((axResp) => {
        let resp = axResp.data
        if (resp.code === "0") {
          // NOTE: special processing for login, because token is in the same level as code
          if (path == "/api/Login/Login") {
            resp.data.token = resp.token
          }
          return resp.data
        } else {
          throw resp
        }
      })
      .catch((err) => {
        if (err.response && err.response.status !== 200) {
          throw {
            status: err.response.status,
          }
        } else {
          throw err
        }
      })
  },
}

/* 
usage:
  async f() {
    try {
      let data = await api.GetUser({
        name: "",
      })
      console.log(data)
    } catch(err) {
      console.log(err)
    }
  }
*/

/* 
usage: getArrayFilterData("EnumUser", ["gender"])
result:
  [
    {
      name: "gender",
      title: "性别",
      tag: "enum",
      list: [
        {
          name: "male",
          title: "男",
          selected: false,
        },
        {
          name: "female",
          title: "女",
          selected: false,
        },
      ],
    },
  ]
 */
const Enum = require("./enum.js")

function getArrayFilterData(enumEntityName, includeList) {
  let out = []

  let entity = Enum[enumEntityName]
  for (let fieldName of Object.keys(entity)) {
    if (includeList.indexOf(fieldName) < 0) {
      continue
    }

    let fieldValue = entity[fieldName]
    let field = {
      name: fieldName,
      title: fieldValue.title,
      tag: "enum",
    }

    let enumValue = fieldValue.value
    let eList = []
    for (let enumName of Object.keys(enumValue)) {
      eList.push({
        name: enumName,
        title: enumValue[enumName].title,
        selected: false,
      })
    }

    field.list = eList
    out.push(field)
  }

  return out
}
